# -- coding: utf-8 --
import random
from airtest.aircv import *
from airtest import aircv
from airtest.utils.transform import TargetPos
from wda import Element
from airtest.core.api import *
from mier_sdk.Robot import Robot
from PIL import Image
from mier_sdk.Robot import  Hex_to_RGB


class Script():
    def __init__( self,wda_airtest,q,Ocr,wda_appium):

        self.screen = None
        self.Ocr = Ocr
        #设备消息队列
        self.q = q
        #appium_client
        self.wda = wda_appium
        #self.ui = client.ui
        #airtest模块
        self.client = wda_airtest
        #self.GM = client.ui.GM
        #图色
        self.robot = Robot()
        #控件
        #self.poco = iosPoco()
        #设备client对象
        self.udid = self.client.uuid.split('//')[1]
        #界面数据存放
        self.q.put([self.udid, 1, '服务已启动'])
        self.q.put([self.udid, 2, '服务已启动'])
        self.q.put([self.udid, 3, '服务已启动'])
        self.q.put([self.udid, 4, '服务已启动'])

    # 滑动
    def swipe_1(self,fpos, tpos, duration=0.5, steps=5, fingers=1):
        # trans pos of swipe
        fx, fy = fpos[0],fpos[1]
        tx, ty =  tpos[0], tpos[1]

        self.client.swipe((fx /1123 , fy /1998),
                          (tx/1123 , ty /1998), duration,steps, fingers)


    def 多点找色(self,tab, sim=15):
        try:
            for tab_pose in tab:
                r, g, b = self.screen[tab_pose[1], tab_pose[0]]
                #print(r,g,b)
                rgb = Hex_to_RGB(tab_pose[2])
                if abs(r - rgb[2]) > sim:
                    return False
                if abs(g - rgb[1]) > sim:
                    return False
                if abs(b - rgb[0]) > sim:
                    return False
            # 获取当前点的颜色
            return True
        except Exception:
            return False

    def get_screen(self):
        return self.client.snapshot(quality=30,max_size = 100)

    def rand_int(self, x, y):
        return random.randint(x,y)

    def rand_folat(self,x, y):
        return random.randint(1000 * x, 1000 * y) / 1000

    def ocrtext_pose(self,tab,white_list = None,compress_size = 480):
        try:
            # 裁剪
            new_res = aircv.crop_image(self.screen, (tab[0], tab[1], tab[2], (tab[3])))
            ocr_1 = self.Ocr.findText(Image.fromarray(new_res),white_list = white_list,is_draw=False,compress_size=compress_size)
            ocr_list = []
            if white_list :
                pass
            else:
                white_list = '1111'
            print('计算前:',ocr_1)
            if len(ocr_1) > 0 :
                for ocr_e in ocr_1:
                    if len(ocr_e) > 0 :
                        if white_list in ocr_e[0] :
                            ocr_list.append([ocr_e[0],[ ocr_e[1][0]+tab[0],ocr_e[1][1]+tab[1]  , ocr_e[1][2]+tab[0],ocr_e[1][3]+tab[1] ]])
            print('计算后:', ocr_list)
            return ocr_list

        except Exception as e :
            print('报错',e)
            return []


    def ocrtext_text(self,tab,white_list=None,compress_size = None):
        try:
            # 裁剪
            new_res = aircv.crop_image(self.screen, (tab[0], tab[1], tab[2], (tab[3])))
            if white_list:
                ocr_1 = self.Ocr.findText(Image.fromarray(new_res),white_list=white_list,is_draw=False,compress_size=compress_size)
            else:
                ocr_1 = self.Ocr.findText(Image.fromarray(new_res), white_list=None, is_draw=False,
                                           compress_size=compress_size)
            print('text计算前:',ocr_1)
            text = ''

            if len(ocr_1) > 0 :
                for ocr_e in ocr_1:
                    if len(ocr_e) > 0 :
                        text = text + ocr_e[0]
            print('text计算后:', text)
            return text
        except Exception as e :
            print('报错:',e)
            return ''

    def 区域找色(self,tab, tab1,sim =67):
        # 裁剪
        try:
            x,y  =  self.robot.findMultiColorInRegionFuzzy(self.screen,tab1[0],tab1[1],sim,tab[0], tab[1], tab[2], tab[3])
            return x, y
        except Exception :
            return -1,-1


    def click_4(self, tab):
        x = tab[0]
        y = tab[1]
        z = tab[2]
        w = tab[3]
        a = random.randint(x, z)
        b = random.randint(y, w)
        print('点击:', a, '---', b)
        self.client.touch((a, b), duration=random.randint(30, 150) / 1000)

    def click_2(self, a, b):
        self.client.touch((a, b), duration=random.randint(30, 100) / 1000)

    def swipe(self, tab, tab1, sleep):
        x = self.rand_int(tab[0], tab[2] + 1)
        y = self.rand_int(tab[1], tab[3] + 1)
        x1 = self.rand_int(tab1[0], tab1[2] + 1)
        y1 = self.rand_int(tab1[1], tab1[3] + 1)
        print(x, '--', y, '--', x1, '--', y1)
        self.client.swipe((x, y), (x1, y1), sleep)

     # 范围找图
    def find_pic(self, filename, range_tab, sim=0.7):
        new_res = aircv.crop_image(self.screen, (range_tab[0], range_tab[1], range_tab[2], range_tab[3]))
        s = Template(filename, threshold=sim, scale_step=0.005)
        match_result = s._cv_match(new_res)
        if not match_result:
            return -1, -1
        focus_pos = TargetPos().getXY(match_result, s.target_pos)
        print(focus_pos)
        return focus_pos[0] + range_tab[0], focus_pos[1] + range_tab[1]


    def run(self):
        #import scripts.script1
        #变量

        image_11 = ["0x1a0c1b", "23|0|0x290e1f,47|8|0xfeffff,59|10|0xfff9ff,81|15|0x2e1125"]
        image_1 = ["0x3d3c3a", "17|13|0x3f3e3c,-1|36|0x3a3935"]
        image_年龄16 = ["0xfdb547", "25|0|0xffb341,45|6|0xfcb444,41|44|0xfcb73e,32|37|0xfefbf6,17|29|0xfcfdf5,49|87|0x373634,53|87|0x31302e,55|87|0x343331"]
        while 1:
            try:

                self.screen = self.get_screen()
                if exists(Template(r'images/zidong.png',threshold = 0.65),):
                    print('存在')
                else:
                    print('不存在')
                print('循环')

                # self.screen = self.get_screen()
                # x, y = self.区域找色([4, 99, 96, 235], image_年龄16)
                # if x > 0:
                #     print('找到')
                # else:
                #     print('没找到')

                # print(self.client.uuid)
                # if self.client.is_pad:
                #     print('是IPAD')
                # else:
                #     print('不是IPAD')
                # #self.client.home()
                # #self.client.text('www.baidu.com',enter = True)
                # # if self.client.alert_exists():
                # #     print(self.client.driver.alert.text)
                # print(self.wda.app_current())
                # x, y = self.区域找色([241, 157, 379, 333], image_1)
                # if x > 0:
                #     pass

                # se = self.wda.session('')
                # e = Element()
                # self.wda.Element.pinch(0.5,-1)



                # text = self.ocrtext_text([852, 179, 965, 425],compress_size=480)
                # print(text)
                # x, y = self.区域找色([233, 350, 410, 544], image_1)
                # if x > 0:
                #     print(x,y)
                # else:
                #     print('没找到')


            except Exception as e:
                print(f'lian报错:{e}')
                self.q.put([self.udid,3,f'报错:{e}'])
                self.q.put([self.udid,2,'连接断开,重新运行'])
                break



